package ThreadPool;

import javax.swing.plaf.synth.SynthOptionPaneUI;
import java.util.concurrent.*;

public class ExecutorTest implements Callable<Object>{

    // 重写Callable接口的call方法
    @Override
    public Object call() {

        int i = 0;
        try{
            while (i++<5){
                System.out.println(Thread.currentThread().getName()+"的run()方法正在执行~");
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return i;
    }

    public static void main(String[] args) throws InterruptedException, ExecutionException {

        // 创建接口实现类的实例对象
        ExecutorTest executor = new ExecutorTest();

        // 使用executors线程执行器创建线程池
        ExecutorService service = Executors.newCachedThreadPool();

        // 将Callable接口实现类对象提交到线程池进行管理
        Future<Object> result1 =  service.submit(executor);
        Future<Object> result2 =  service.submit(executor);
        Future<Object> result3 =  service.submit(executor);

        // 关闭线程池
        service.shutdown();

        // 对于有返回值的线程任务，获取执行结果
        System.out.println("thread-1:"+result1.get());
        System.out.println("thread-2:"+result2.get());
        System.out.println("thread-3:"+result3.get());

    }
}
